package stack;

import java.util.concurrent.atomic.AtomicReference;

import stack.StackWorker.WorkerInfo;

public class CentralStack {

	AtomicReference<Cell> top_;

	public CentralStack() {
		top_ = new AtomicReference<Cell>(null);
	}

	public boolean tryPerformStackOp(WorkerInfo workerInfo) {
		Cell top, next;
		/*if (Math.random()<0.2){
			return false;
	}*/
		switch (workerInfo.op_) {
		case StackWorker.PUSH:
			top = top_.get();
			workerInfo.cell_.next_ = top;
			if (top_.compareAndSet(top, workerInfo.cell_)) {
				//workerInfo.logPush(System.currentTimeMillis(), this.getClass().getName());
				workerInfo.success_++;
				return true;
			} else {
				workerInfo.failure_++;
				workerInfo.cell_.next_=null; 
				return false;

			}


		case StackWorker.POP:
			top = top_.get();
			if(top==null){
				workerInfo.cell_ =  new Cell("EMPTY");
			//	workerInfo.logPop(System.currentTimeMillis(), this.getClass().getName());
				workerInfo.success_++;
				return true;
			}
			next = top.next_;
			if (top_.compareAndSet(top, next)) {
				workerInfo.cell_ = top;
				//workerInfo.logPop(System.currentTimeMillis(), this.getClass().getName());
				workerInfo.success_++;
				return true;
			} else {
				workerInfo.failure_++;
				return false;

			}



		default:
			return false;

		}

	}

	public int size() {
		int size=0;
		Cell top = top_.get();
		while(top!=null){
			top=top.next_;
			size++;
		}
		return size;
	}





}
